package com.zsn.demo.service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author: cml
 * @since: 2022/11/9 10:39
 * @description:
 */
public class TestThreadPool {
    public static void main(String[] args) {
        final int corePoolSize = 6;
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, corePoolSize+3, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1), handler);
        Runnable runnable = () ->{
            try {
                AtomicLong atomicLong = new AtomicLong();
                Long[] longArray = {1l, 2l, 3l, 4l, 5l, 6l};
                final CountDownLatch latch = new CountDownLatch(longArray.length);
                for (int i = 0; i < longArray.length; i++) {
                    ThreadPoolTask task = new ThreadPoolTask(longArray[i], latch, atomicLong);
                    executor.execute(task);
                }
                latch.await();
                System.out.println("和为：" + atomicLong);
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        executor.execute(runnable);
    }
}
